/**
 * Created by Ng on 2023/11/16
 */

/**
 * localStorage | sessionStorage
 * IE8、Chrome 5 及以上支持
 * 两者存储大小为 5M 或 更大
 * 一般写为 `window.localStorage.`， 其前缀 window. 可省略
 * localStorage    存储持久数据，浏览器关闭后数据不丢失除非主动删除数据
 * sessionStorage  数据在当前浏览器窗口关闭后自动删除
 */

/**
 * @description 本地存储，不填默认 localStorage 类型
 * @param {String} key 
 * @param {String | Object} value 
 * @param {String} storage 
 * @returns {Boolean}
 */
export function setStorage(key, value, storage = 'localStorage') {
  if (!key) return
  if (typeof value !== 'string') {
    value = JSON.stringify(value)
  }
  if (storage === 'sessionStorage') {
    // IE8、Chrome 5 及以上支持
    if (!window.sessionStorage) return
    return window.sessionStorage.setItem(key, value)
  }
  // IE8、Chrome 5 及以上支持
  if (!window.localStorage) return
  return window.localStorage.setItem(key, value)
}

/**
 * @description 获取本地存储，不填默认 localStorage 类型
 * @param {String} key 
 * @param {String} storage 
 * @returns {String | Object | Null}
 */
export function getStorage(key, storage = 'localStorage') {
  if (!key) return
  let value
  if (storage === 'sessionStorage') {
    if (!window.sessionStorage) return
    value = window.sessionStorage.getItem(key)
  } else {
    if (!window.localStorage) return
    value = window.localStorage.getItem(key)
  }
  // 根据需要 JSON.parse(value)
  if (typeof value !== 'string') {
    return JSON.parse(value)
  }
  return value
}

/**
 * @description 删除指定 key 本地存储，不填默认 localStorage 类型
 * @param {String} key 
 * @param {String} storage 
 * @returns {Boolean}
 */
export function removeStorage(key, storage = 'localStorage') {
  if (!key) return
  if (storage === 'sessionStorage') {
    if (!window.sessionStorage) return
    return window.sessionStorage.removeItem(key)
  }
  if (!window.localStorage) return
  return window.localStorage.removeItem(key)
}

/**
 * @description 清除全部本地存储
 * @param {String} storage 
 * @returns {Boolean}
 */
export function clearStorage(storage = 'localStorage') {
  if (storage === 'sessionStorage') {
    if (!window.sessionStorage) return
    return window.sessionStorage.clear()
  }
  if (!window.localStorage) return
  return window.localStorage.clear()
}
